//
//  File.swift
//  
//
//  Created by czi on 2023/12/13.
//
import Foundation

@attached(extension, conformances: Formable, names: named(asData))
public macro Formable() = #externalMacro(module: "LSRequestMacros", type: "FormableMacro")


@attached(peer)
public macro HTTPForm<Form: Formable>() = #externalMacro(module: "LSRequestMacros", type: "HTTPFormMacro")

public protocol Formable {
    func asData() -> Data?
}

public extension Formable {
    func asData() -> Data? {
        let properties = Mirror(reflecting: self)
        guard !properties.children.isEmpty else {
            return nil
        }

        let querys = properties.children.reduce(into: [URLQueryItem]()) { previous, next in
            if let label = next.label {
                let item = URLQueryItem(name: label, value: "\(next.value)")
                previous.append(item)
            }
        }
        var form = URLComponents()
        form.queryItems = querys
        return form.query?.data(using: .utf8)
    }
}
